package com.blog.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.blog.admin.service.TagService;
import com.blog.common.core.utils.PageUtils;
import com.blog.common.core.web.page.TableDataInfo;
import com.blog.common.domain.dto.TagDto;
import com.blog.common.domain.entity.Tag;
import com.blog.common.domain.dto.ConditionDto;
import com.blog.common.domain.vo.TagVo;
import com.blog.common.mapper.dao.TagMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 标签 服务实现类
 * </p>
 *
 * @author Valerie
 * @since 2023-03-11
 */
@Service
public class TagServiceImpl extends ServiceImpl<TagMapper, Tag> implements TagService {

    @Resource
    private TagMapper tagMapper;

    @Override
    public List<TagVo> listTagsBySearch(ConditionDto condition) {
        List<Tag> tagList = new LambdaQueryChainWrapper<>(tagMapper)
                .select(Tag::getId, Tag::getTagName)
                .like(StrUtil.isNotBlank(condition.getKeywords()), Tag::getTagName, condition.getKeywords())
                .orderByDesc(Tag::getId)
                .list();

        return BeanUtil.copyToList(tagList, TagVo.class);
    }

    @Override
    public TableDataInfo<TagVo> listTags(ConditionDto condition) {
        List<TagVo> tagList;
        long size;
        if (Objects.nonNull(condition.getByPage()) && !condition.getByPage()){
            tagList = BeanUtil.copyToList(tagMapper.selectList(null), TagVo.class);
            size = tagList.size();
        }else {
            Page<TagVo> tagPage = tagMapper.selectTagVoList(PageUtils.getPage());
            tagList = tagPage.getRecords();
            size = tagPage.getTotal();
        }
        return new TableDataInfo<>(tagList, size);
    }


    @Override
    public void saveTag(String tags) {
        Tag tag = Tag.builder()
                .tagName(tags)
                .build();
        this.save(tag);
    }

    @Override
    public TagVo getTagById(Serializable tagId) {
        Tag tag = this.getById(tagId);
        return BeanUtil.copyProperties(tag, TagVo.class);
    }

    @Override
    public void updateTag(TagDto tagDto) {
        this.update(
                new LambdaUpdateWrapper<Tag>()
                        .eq(Tag::getId, tagDto.getId())
                        .set(Tag::getTagName, tagDto.getTagName())
        );
    }
}
